// 全局变量
let frameBufferData = [];
let isRunning = false;
let updateInterval;

// 矩形选择相关变量
let isSelecting = false;
let startCell = null;
let selectedCells = [];
let selectionBounds = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('T5 虚拟机界面初始化...');
    
    // 绑定按钮事件
    bindButtonEvents();
    
    // 初始加载帧缓冲区
    loadFrameBuffer();
    
    // 初始加载状态
    updateStatus();
});

// 绑定按钮事件
function bindButtonEvents() {
    console.log('绑定按钮事件...');
    
    const runBtn = document.getElementById('runBtn');
    const stepBtn = document.getElementById('stepBtn');
    const resetBtn = document.getElementById('resetBtn');
    const stopBtn = document.getElementById('stopBtn');
    const insertCoinBtn = document.getElementById('insertCoinBtn');
    const loadAsmBtn = document.getElementById('loadAsmBtn');

    console.log('找到按钮:', {
        runBtn: !!runBtn,
        stepBtn: !!stepBtn,
        resetBtn: !!resetBtn,
        stopBtn: !!stopBtn,
        insertCoinBtn: !!insertCoinBtn,
        loadAsmBtn: !!loadAsmBtn
    });

    if (runBtn) {
        runBtn.addEventListener('click', runVM);
        console.log('绑定运行按钮');
    }
    if (stepBtn) {
        stepBtn.addEventListener('click', stepVM);
        console.log('绑定单步按钮');
    }
    if (resetBtn) {
        resetBtn.addEventListener('click', resetVM);
        console.log('绑定重置按钮');
    }
    if (stopBtn) {
        stopBtn.addEventListener('click', stopVM);
        console.log('绑定停止按钮');
    }
    if (insertCoinBtn) {
        insertCoinBtn.addEventListener('click', insertCoin);
        console.log('绑定投币按钮');
    }
    if (loadAsmBtn) {
        loadAsmBtn.addEventListener('click', loadAssemblyCode);
        console.log('绑定汇编代码加载按钮');
    } else {
        console.error('未找到汇编代码加载按钮！');
    }
}

// 加载汇编代码函数
function loadAssemblyCode() {
    console.log('开始加载汇编代码...');
    
    const asmCode = document.getElementById('asmCode');
    const asmStatus = document.getElementById('asmStatus');
    
    console.log('找到元素:', {
        asmCode: !!asmCode,
        asmStatus: !!asmStatus
    });
if (!asmCode || !asmStatus) {
        console.error('找不到汇编代码元素');
        return;
    }
    
    const codeText = asmCode.value.trim();
    console.log('输入的代码:', codeText);
    
    if (!codeText) {
        asmStatus.innerHTML = '<span style="color: red;">请输入汇编代码</span>';
        console.log('汇编代码为空');
        return;
    }
    
    console.log('原始汇编代码:', codeText);
    
    // 服务器期望接收字符串，而不是数组
    // 直接将用户输入的字符串发送给服务器
    asmStatus.innerHTML = '<span style="color: blue;">正在加载汇编代码...</span>';
    
    // 调用 /api/asm 接口，发送字符串而不是数组
    console.log('发送POST请求到 /api/asm');
    fetch('/api/asm', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ code: codeText })  // 直接发送字符串
    })
    .then(response => {
        console.log('API响应状态:', response.status);
        return response.json();
    })
    .then(data => {
        console.log('API响应数据:', data);
        if (data.success) {
            asmStatus.innerHTML = '<span style="color: green;">汇编代码加载成功！</span>';
            // 更新状态和帧缓冲区
            updateStatus();
            loadFrameBuffer();
        } else {
            asmStatus.innerHTML = `<span style="color: red;">加载失败: ${data.error || '未知错误'}</span>`;
        }
    })
    .catch(error => {
        console.error('网络错误:', error);
        asmStatus.innerHTML = `<span style="color: red;">网络错误: ${error.message}</span>`;
    });
}

// 运行虚拟机
function runVM() {
    if (isRunning) return;
    
    console.log('启动虚拟机运行...');
    isRunning = true;
    updateButtonStates();
    
    // 调用/run端点让虚拟机持续运行直到停机或coin用完
    fetch('/api/run', { method: 'POST' })
        .then(response => response.json())
        .then(data => {
            // 运行完成后更新界面
            loadFrameBuffer();
            updateStatus();
            console.log('虚拟机运行完成，结果:', data.result);
            
            // 自动停止运行状态
            isRunning = false;
            updateButtonStates();
        })
        .catch(error => {
            console.error('请求失败:', error);
            
            // 出错时也停止运行状态
            isRunning = false;
            updateButtonStates();
        });
}

// 单步执行
function stepVM() {
    if (isRunning) return;
    
    console.log('执行单步操作...');
    
    fetch('/api/step', { method: 'POST' })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadFrameBuffer();
                updateStatus();
            } else {
                console.error('单步执行失败:', data.error);
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
        });
}

// 重置虚拟机
function resetVM() {
    console.log('重置虚拟机...');
    
    if (isRunning) {
        stopVM();
    }
    
    fetch('/api/reset', { method: 'PUT' })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadFrameBuffer();
                updateStatus();
                console.log('虚拟机重置成功');
            } else {
                console.error('重置失败:', data.error);
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
        });
}

// 投币功能
function insertCoin() {
    console.log('投币...');
    
    fetch('/api/insert-coin', { method: 'POST' })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                loadFrameBuffer();
                updateStatus();
                console.log('投币成功，当前硬币:', data.coins);
            } else {
                console.error('投币失败:', data.error);
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
        });
}

// 停止虚拟机
function stopVM() {
    console.log('停止虚拟机...');
    
    isRunning = false;
    if (updateInterval) {
        clearInterval(updateInterval);
        updateInterval = null;
    }
    
    updateButtonStates();
}

// 更新按钮状态
function updateButtonStates() {
    const runBtn = document.getElementById('runBtn');
    const stepBtn = document.getElementById('stepBtn');
    const stopBtn = document.getElementById('stopBtn');
    
    if (isRunning) {
        if (runBtn) runBtn.disabled = true;
        if (stepBtn) stepBtn.disabled = true;
        if (stopBtn) stopBtn.disabled = false;
    } else {
        if (runBtn) runBtn.disabled = false;
        if (stepBtn) stepBtn.disabled = false;
        if (stopBtn) stopBtn.disabled = true;
    }
}

// 加载帧缓冲区
function loadFrameBuffer() {
    fetch('/api/frame-buffer')
        .then(response => response.json())
        .then(data => {
            if (data.success && data.frameBuffer) {
                frameBufferData = data.frameBuffer;
                renderFrameBuffer();
            } else {
                console.error('加载帧缓冲区失败:', data.error);
                showError('无法加载帧缓冲区数据');
            }
        })
        .catch(error => {
            console.error('请求帧缓冲区失败:', error);
            showError('网络错误：无法连接到服务器');
        });
}

// 渲染帧缓冲区
function renderFrameBuffer() {
    console.log('开始渲染帧缓冲区...');
    
    const frameBufferElement = document.getElementById('frameBuffer');
    if (!frameBufferElement) {
        console.error('帧缓冲区元素未找到');
        return;
    }
    
    // 清空现有内容
    frameBufferElement.innerHTML = '';
    
    if (!frameBufferData || frameBufferData.length === 0) {
        console.log('帧缓冲区数据为空');
        frameBufferElement.innerHTML = '<div class="loading">帧缓冲区为空</div>';
        return;
    }
    
    console.log('帧缓冲区数据长度:', frameBufferData.length);
    console.log('帧缓冲区数据内容:', frameBufferData);
    
    // 直接使用服务器返回的HTML内容
    // frameBufferData是frame-buffer.html的完整HTML内容
    frameBufferElement.innerHTML = frameBufferData;
    
    // 重新创建selectionBox元素，因为上面的innerHTML会覆盖它
    const selectionBox = document.createElement('div');
    selectionBox.id = 'selectionBox';
    selectionBox.className = 'selection-box';
    selectionBox.style.display = 'none';
    frameBufferElement.appendChild(selectionBox);
    
    console.log('帧缓冲区渲染完成，容器内容:', frameBufferElement.innerHTML);
    
    // 添加矩形选择功能
    addRectangleSelection();
}

// 添加矩形选择功能
function addRectangleSelection() {
    console.log('开始添加矩形选择功能...');
    
    const tableContainer = document.getElementById('frameBuffer');
    const selectionBox = document.getElementById('selectionBox');
    
    console.log('查找的元素:', {
        tableContainer: !!tableContainer,
        selectionBox: !!selectionBox
    });
    
    if (!tableContainer) {
        console.error('表格容器元素未找到，跳过矩形选择功能');
        return;
    }
    
    if (!selectionBox) {
        console.error('选择框元素未找到，尝试重新创建...');
        // 如果selectionBox不存在，重新创建它
        const newSelectionBox = document.createElement('div');
        newSelectionBox.id = 'selectionBox';
        newSelectionBox.className = 'selection-box';
        newSelectionBox.style.display = 'none';
        tableContainer.appendChild(newSelectionBox);
        console.log('重新创建了selectionBox元素');
        return addRectangleSelection(); // 重新调用函数
    }
    
    // 检查frameBuffer容器内的内容
    console.log('frameBuffer容器内容:', tableContainer.innerHTML);
    
    // 智能查找表格元素
    let table = document.getElementById('FRAME-BUFFER');
    if (!table) {
        console.log('未找到ID为FRAME-BUFFER的表格，尝试查找容器内的第一个表格');
        // 如果没有找到FRAME-BUFFER表格，尝试查找第一个表格
        table = tableContainer.querySelector('table');
        if (!table) {
            console.error('未找到任何表格元素，跳过矩形选择功能');
            console.log('frameBuffer容器内的所有元素:', tableContainer.children);
            return;
        }
        console.log('找到表格元素，但ID不是FRAME-BUFFER');
    }
    
    console.log('找到表格:', table);
    console.log('表格行数:', table.rows.length);
    if (table.rows.length > 0) {
        console.log('第一行的单元格数:', table.rows[0].cells.length);
    }
    
    // 确保所有单元格都有正确的data-row和data-col属性
    function ensureCellAttributes() {
        console.log('确保单元格属性...');
        const rows = table.rows;
        for (let i = 0; i < rows.length; i++) {
            const cells = rows[i].cells;
            for (let j = 0; j < cells.length; j++) {
                const cell = cells[j];
                if (!cell.dataset.row) {
                    cell.dataset.row = i;
                }
                if (!cell.dataset.col) {
                    cell.dataset.col = j;
                }
            }
        }
        console.log('单元格属性设置完成');
    }
    
    // 获取单元格的行列索引
    function getCellIndex(cell) {
        // 确保单元格有正确的属性
        if (!cell.dataset.row || !cell.dataset.col) {
            // 如果单元格没有属性，尝试从表格结构推断
            const rowIndex = cell.parentNode.rowIndex;
            const cellIndex = cell.cellIndex;
            return {
                row: rowIndex,
                col: cellIndex
            };
        }
        return {
            row: parseInt(cell.dataset.row),
            col: parseInt(cell.dataset.col)
        };
    }
    
    // 获取鼠标所在的单元格
    function getCellFromPoint(x, y) {
        const elements = document.elementsFromPoint(x, y);
        for (const el of elements) {
            if (el.tagName === 'TD') {
                return el;
            }
        }
        return null;
    }
    
    // 清除所有选择
    function clearSelection() {
        selectedCells.forEach(cell => {
            cell.classList.remove('selected');
        });
        selectedCells = [];
        selectionBounds = null;
    }
    
    // 选择矩形区域
    function selectRect(startRow, startCol, endRow, endCol) {
        clearSelection();
        
        const minRow = Math.min(startRow, endRow);
        const maxRow = Math.max(startRow, endRow);
        const minCol = Math.min(startCol, endCol);
        const maxCol = Math.max(startCol, endCol);
        
        selectionBounds = { minRow, maxRow, minCol, maxCol };
        
        for (let i = minRow; i <= maxRow; i++) {
            for (let j = minCol; j <= maxCol; j++) {
                const cell = table.rows[i].cells[j];
                if (cell) {
                    cell.classList.add('selected');
                    selectedCells.push(cell);
                }
            }
        }
    }
    
    // 复制选中内容到剪贴板
    function copySelectionToClipboard() {
        if (!selectionBounds || selectedCells.length === 0) return;
        
        const { minRow, maxRow, minCol, maxCol } = selectionBounds;
        
        // 构建文本内容 - 使用制表符分隔列，换行符分隔行
        let textContent = '';
        for (let i = minRow; i <= maxRow; i++) {
            let rowContent = '';
            for (let j = minCol; j <= maxCol; j++) {
                const cell = table.rows[i].cells[j];
                if (cell) {
                    rowContent += cell.textContent;
                    // if (j < maxCol) rowContent += '\t'; // 制表符分隔列
                }
            }
            textContent += rowContent;
            if (i < maxRow) textContent += '\n'; // 换行符分隔行
        }
        
        // 使用Clipboard API复制到剪贴板
        navigator.clipboard.writeText(textContent)
            .then(() => {
                console.log('内容已复制到剪贴板');
            })
            .catch(err => {
                // 降级方案
                const textArea = document.createElement('textarea');
                textArea.value = textContent;
                document.body.appendChild(textArea);
                textArea.select();
                document.execCommand('copy');
                document.body.removeChild(textArea);
                console.log('使用降级方案复制内容到剪贴板');
            });
    }
    
    // 确保单元格属性
    ensureCellAttributes();
    
    // 鼠标按下事件
    tableContainer.addEventListener('mousedown', function(e) {
        console.log('鼠标按下事件触发', e.clientX, e.clientY);
        
        if (e.button !== 0) return;
        
        const cell = getCellFromPoint(e.clientX, e.clientY);
        console.log('找到的单元格:', cell);
        
        if (!cell) return;
        
        isSelecting = true;
        startCell = cell;
        
        const rect = tableContainer.getBoundingClientRect();
        selectionBox.style.left = (e.clientX - rect.left) + 'px';
        selectionBox.style.top = (e.clientY - rect.top) + 'px';
        selectionBox.style.width = '0';
        selectionBox.style.height = '0';
        selectionBox.style.display = 'block';
        
        console.log('开始选择，起始单元格:', startCell);
        
        e.preventDefault();
    });
    
    // 鼠标移动事件
    tableContainer.addEventListener('mousemove', function(e) {
        if (!isSelecting) return;
        
        console.log('鼠标移动事件触发', e.clientX, e.clientY);
        
        const rect = tableContainer.getBoundingClientRect();
        const currentX = e.clientX - rect.left;
        const currentY = e.clientY - rect.top;
        
        const startX = parseFloat(selectionBox.style.left);
        const startY = parseFloat(selectionBox.style.top);
        
        selectionBox.style.width = Math.abs(currentX - startX) + 'px';
        selectionBox.style.height = Math.abs(currentY - startY) + 'px';
        
        if (currentX < startX) {
            selectionBox.style.left = currentX + 'px';
        }
        
        if (currentY < startY) {
            selectionBox.style.top = currentY + 'px';
        }
        
        const endCell = getCellFromPoint(e.clientX, e.clientY);
        if (endCell) {
            const startIdx = getCellIndex(startCell);
            const endIdx = getCellIndex(endCell);
            console.log('选择区域:', startIdx, endIdx);
            selectRect(startIdx.row, startIdx.col, endIdx.row, endIdx.col);
        }
    });
    
    // 鼠标释放事件
    document.addEventListener('mouseup', function() {
        if (!isSelecting) return;
        
        console.log('鼠标释放事件触发');
        
        isSelecting = false;
        selectionBox.style.display = 'none';
        console.log('选择完成，选中单元格数:', selectedCells.length);
    });
    
    // 键盘事件处理
    document.addEventListener('keydown', function(e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 'c') {
            if (selectedCells.length > 0) {
                copySelectionToClipboard();
                e.preventDefault();
            }
        }
    });
    
    console.log('矩形选择功能添加完成');
}

// 更新状态信息
function updateStatus() {
    fetch('/api/state')
        .then(response => response.json())
        .then(data => {
            updateStatusDisplay(data);
        })
        .catch(error => {
            console.error('请求状态失败:', error);
        });
}

// 更新状态显示
function updateStatusDisplay(status) {
    const pcElement = document.getElementById('pcValue');
    const spElement = document.getElementById('spValue');
    const cyclesElement = document.getElementById('cyclesValue');
    const coinsElement = document.getElementById('coinsValue');
    
    if (pcElement && status.pc !== undefined) {
        pcElement.textContent = status.pc;
    }
    
    if (spElement && status.sp !== undefined) {
        spElement.textContent = status.sp;
    }
    
    if (cyclesElement && status.cycles !== undefined) {
        cyclesElement.textContent = status.cycles;
    }
    
    if (coinsElement && status.coins !== undefined) {
        coinsElement.textContent = status.coins;
    }
}

// 显示错误信息
function showError(message) {
    const frameBufferElement = document.getElementById('frameBuffer');
    if (frameBufferElement) {
        frameBufferElement.innerHTML = `<div class="loading" style="color: #e53e3e;">${message}</div>`;
    }
    
    // 也可以显示通知
    console.error('错误:', message);
}

// 工具函数：格式化数字
function formatNumber(num) {
    if (num === undefined || num === null) return 'N/A';
    return num.toString();
}

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 导出函数供全局使用（如果需要）
window.T5VM = {
    run: runVM,
    step: stepVM,
    reset: resetVM,
    stop: stopVM,
    loadFrameBuffer: loadFrameBuffer,
    updateStatus: updateStatus
};